package com.song.EMS.mvc;


import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.DriverManager;


/**
 * @author song
 */
public class DispatcherServlet extends HttpServlet {

    @Override
    public void init(ServletConfig config) throws ServletException {
        System.out.println("初始化");
        String path = config.getInitParameter("app");
        InputStream is = DispatcherServlet.class.getClassLoader().getResourceAsStream(path);
        HeaderMapping.load(is);
        System.out.println("初始化结束");
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //获取前端请求地址uri
            String uri = req.getRequestURI();
            //通过uri找到对应请求映射
            Mapping mapping = HeaderMapping.getMapping(uri);
            if (mapping == null) {
                resp.sendError(404,"映射地址不存在"+uri);
                return;
            }
            Object o = mapping.getObject();
            Method method = mapping.getMethod();
            Object invoke = method.invoke(o, req, resp);
            //获取方法返回类型
            DispatcherType type = mapping.getType();
            switch (type) {
                case TEXT:
                    resp.getWriter().write((String) invoke);
                    break;
                case VIEW:
                    resp.sendRedirect((String) invoke);
                    break;
                default:
                    break;
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

    }
    @Override
    public void destroy() {
        super.destroy();
    }

}
